import { useState } from 'react';
import { useProviderStore } from '../stores/useProviderStore';
import { Button } from '../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Switch } from '../components/ui/switch';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../components/ui/tabs';
import { Settings, Eye, EyeOff, CheckCircle, XCircle } from 'lucide-react';
import { toast } from '../hooks/use-toast';

export default function ProvidersPage() {
  const { availableProviders, updateProviderConfig, isProviderFullyConfigured } = useProviderStore();
  const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});
  const [configs, setConfigs] = useState<Record<string, any>>({});

  const handleConfigChange = (providerName: string, key: string, value: any) => {
    setConfigs(prev => ({
      ...prev,
      [providerName]: {
        ...prev[providerName],
        [key]: value
      }
    }));
  };

  const handleSaveConfig = async (providerName: string) => {
    try {
      await updateProviderConfig(providerName, configs[providerName] || {});
      toast({
        title: "Configuration Saved",
        description: `${providerName} configuration has been updated.`,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to save configuration. Please try again.",
        variant: "destructive",
      });
    }
  };

  const toggleApiKeyVisibility = (providerName: string) => {
    setShowApiKeys(prev => ({
      ...prev,
      [providerName]: !prev[providerName]
    }));
  };

  const getProviderConfig = (providerName: string) => {
    const provider = availableProviders.find(p => p.name === providerName);
    return { ...provider?.config, ...configs[providerName] };
  };

  return (
    <div className="flex flex-col h-full p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">AI Providers</h1>
          <p className="text-slate-600 dark:text-slate-400">
            Configure your AI model providers and API settings
          </p>
        </div>
      </div>

      <div className="flex-1 overflow-auto">
        <Tabs defaultValue="openai" className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            {availableProviders.map((provider) => (
              <TabsTrigger key={provider.name} value={provider.name} className="flex items-center gap-2">
                {isProviderFullyConfigured(provider.name) ? (
                  <CheckCircle className="h-4 w-4 text-green-500" />
                ) : (
                  <XCircle className="h-4 w-4 text-red-500" />
                )}
                {provider.name}
              </TabsTrigger>
            ))}
          </TabsList>

          {availableProviders.map((provider) => (
            <TabsContent key={provider.name} value={provider.name} className="mt-6">
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        <Settings className="h-5 w-5" />
                        {provider.name} Configuration
                      </CardTitle>
                      <CardDescription>
                        Configure your {provider.name} API settings and preferences
                      </CardDescription>
                    </div>
                    <Badge variant={isProviderFullyConfigured(provider.name) ? "default" : "destructive"}>
                      {isProviderFullyConfigured(provider.name) ? "Configured" : "Not Configured"}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent className="space-y-6">
                  {/* API Key */}
                  <div className="space-y-2">
                    <Label htmlFor={`${provider.name}-api-key`}>API Key</Label>
                    <div className="flex gap-2">
                      <Input
                        id={`${provider.name}-api-key`}
                        type={showApiKeys[provider.name] ? "text" : "password"}
                        value={getProviderConfig(provider.name).apiKey || ''}
                        onChange={(e) => handleConfigChange(provider.name, 'apiKey', e.target.value)}
                        placeholder="Enter your API key"
                        className="flex-1"
                      />
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => toggleApiKeyVisibility(provider.name)}
                      >
                        {showApiKeys[provider.name] ? (
                          <EyeOff className="h-4 w-4" />
                        ) : (
                          <Eye className="h-4 w-4" />
                        )}
                      </Button>
                    </div>
                  </div>

                  {/* Base URL (for some providers) */}
                  {['openai', 'anthropic'].includes(provider.name.toLowerCase()) && (
                    <div className="space-y-2">
                      <Label htmlFor={`${provider.name}-base-url`}>Base URL (Optional)</Label>
                      <Input
                        id={`${provider.name}-base-url`}
                        value={getProviderConfig(provider.name).baseUrl || ''}
                        onChange={(e) => handleConfigChange(provider.name, 'baseUrl', e.target.value)}
                        placeholder={`https://api.${provider.name.toLowerCase()}.com/v1`}
                      />
                    </div>
                  )}

                  {/* Organization ID (for OpenAI) */}
                  {provider.name.toLowerCase() === 'openai' && (
                    <div className="space-y-2">
                      <Label htmlFor="openai-org-id">Organization ID (Optional)</Label>
                      <Input
                        id="openai-org-id"
                        value={getProviderConfig(provider.name).organizationId || ''}
                        onChange={(e) => handleConfigChange(provider.name, 'organizationId', e.target.value)}
                        placeholder="org-xxxxxxxxxx"
                      />
                    </div>
                  )}

                  {/* Default Model */}
                  <div className="space-y-2">
                    <Label htmlFor={`${provider.name}-model`}>Default Model</Label>
                    <Input
                      id={`${provider.name}-model`}
                      value={getProviderConfig(provider.name).defaultModel || ''}
                      onChange={(e) => handleConfigChange(provider.name, 'defaultModel', e.target.value)}
                      placeholder={
                        provider.name.toLowerCase() === 'openai' ? 'gpt-4' :
                        provider.name.toLowerCase() === 'anthropic' ? 'claude-3-sonnet-20240229' :
                        provider.name.toLowerCase() === 'google' ? 'gemini-pro' :
                        'Enter model name'
                      }
                    />
                  </div>

                  {/* Enable/Disable Provider */}
                  <div className="flex items-center space-x-2">
                    <Switch
                      id={`${provider.name}-enabled`}
                      checked={getProviderConfig(provider.name).enabled !== false}
                      onCheckedChange={(checked) => handleConfigChange(provider.name, 'enabled', checked)}
                    />
                    <Label htmlFor={`${provider.name}-enabled`}>Enable this provider</Label>
                  </div>

                  {/* Save Button */}
                  <div className="flex justify-end">
                    <Button onClick={() => handleSaveConfig(provider.name)}>
                      Save Configuration
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          ))}
        </Tabs>
      </div>
    </div>
  );
}